import { useState, useEffect, useRef } from "react";
import { invoke } from "@tauri-apps/api/core";
import { Link, useNavigate, useLocation } from "react-router-dom";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { Timer } from "./Timer.tsx";
import { UserInterface } from "./UserInterface.tsx";
import { LogicalSize } from '@tauri-apps/api/dpi';
import "./ChangePassword.css"

function ChangePassword() {
  const [oldPassword, setOldPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [message, setMessage] = useState("");
  const navigate = useNavigate();
  const location = useLocation();
  const {
    routeInfo
  } = UserInterface();
  const routeinforef = useRef(routeInfo);
  useEffect(()=> {
    const route_info = {
                user : location.state.routeInfo.user,
                url : location.state.routeInfo.url,
            }
    routeinforef.current = route_info;
    getCurrentWindow().setSize(new LogicalSize(800, 600));
  }, [])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    // 检查新密码是否匹配
    if (newPassword !== confirmPassword) {
      setMessage("New passwords do not match");
      return;
    }
    // 检查新密码复杂度
    const hasDigit = /[0-9]/.test(newPassword);
    const hasLowerCase = /[a-z]/.test(newPassword);
    const hasUpperCase = /[A-Z]/.test(newPassword);
    if (!hasDigit) {
      setMessage("New password must contain at least one digit");
      return;
    } else if (!hasLowerCase) {
      setMessage("New password must contain at least one lowercase letter");
      return;
    } else if (!hasUpperCase) {
      setMessage("New password must contain at least one uppercase letter");
      return;
    }
    if (newPassword.length < 6 || newPassword.length > 13) {
      setMessage("New password must be between 6 and 12 characters");
      return;
    }
    const oldNewPassword = {
      old_password: oldPassword,
      new_password: newPassword,
    }
    try {
      setIsLoading(true);
      const response = await invoke("change_password", { 
        user: routeinforef.current?.user,
        oldNewPassword: oldNewPassword,
        mongodbUrl: routeinforef.current?.url,
      });
      console.log(response);
      setMessage(response as string);
      if ((response as string).includes("successful")) {
        // 延迟2秒后返回文件浏览器页面
        setTimeout(() => {
          navigate("/");
        }, 2000);
      }
    } catch (error) {
      console.error(error);
      setMessage(String(error));
    }
    setIsLoading(false);
  };

  return (
    <main className="container">
      <h1 id="change-password">⚙️Change Password</h1>
      
      <form className="password-form" onSubmit={handleSubmit}>
        <input
          id="input-old-password"
          onChange={(e) => setOldPassword(e.currentTarget.value)}
          type="password"
          placeholder="Enter current password"
          value={oldPassword}
          required
        />
        <input 
          id="input-new-password" 
          onChange={(e) => setNewPassword(e.currentTarget.value)} 
          type="password" 
          placeholder="Enter new password"
          value={newPassword} 
          required
        />
        <input 
          id="input-confirm-password" 
          onChange={(e) => setConfirmPassword(e.currentTarget.value)} 
          type="password" 
          placeholder="Confirm new password"
          value={confirmPassword} 
          required
        />
        <div className="button-container">
          <Link to="/files" state={{ 
                path : location.state.path,
                routeInfo : location.state.routeInfo
              }}>
            <button type="button" id="changepasswordreturn">🔙Return</button>
          </Link>
          <button type="submit" id="changepasswordbutton">✏️Change Password</button>
        </div>
        {message && (
          <div className={message.includes("successful") ? 
            "success-message" : "error-message"}>
            {message}
          </div>
        )}
        {isLoading && (
            <div id="login-loadingbar">
              <div id="login-loading">🔄loading...</div>
              <Timer />
            </div>
        )}
      </form>
    </main>
  );
}

export default ChangePassword;